package cn.lblbc.appassit

import android.Manifest
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import cn.lblbc.appassit.model.AppInfo
import cn.lblbc.appassit.utils.AppExporter
import cn.lblbc.appassit.utils.AppScanner
import cn.lblbc.appassit.utils.ExportResultDialogHelper
import cn.lblbc.appassit.utils.FileNameInputDialog
import cn.lblbc.appassit.utils.FileUtils
import cn.lblbc.appassit.utils.PermissionHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class AppDetailActivity : AppCompatActivity() {

    private lateinit var appInfo: AppInfo
    private lateinit var appExporter: AppExporter
    private lateinit var appScanner: AppScanner
    private lateinit var exportResultDialogHelper: ExportResultDialogHelper
    private lateinit var fileNameInputDialog: FileNameInputDialog
    
    // 存储权限回调
    private var permissionCallback: ((Boolean) -> Unit)? = null
    
    // 卸载应用的广播接收器
    private var uninstallReceiver: android.content.BroadcastReceiver? = null

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            extractAppIcon()
        } else {
            Toast.makeText(this, "需要存储权限才能提取图标", Toast.LENGTH_SHORT).show()
        }
    }

    private val requestManageExternalStorageLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                extractAppIcon()
            } else {
                Toast.makeText(this, "需要管理所有文件权限才能提取图标", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    // 权限请求
    private val storagePermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        permissionCallback?.invoke(allGranted)
        permissionCallback = null
    }

    // Android 11+ 管理外部存储权限
    private val manageStorageLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val granted = Environment.isExternalStorageManager()
            permissionCallback?.invoke(granted)
            permissionCallback = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_app_detail)

        // 初始化组件
        appExporter = AppExporter(this)
        appScanner = AppScanner(this)
        exportResultDialogHelper = ExportResultDialogHelper(this)
        fileNameInputDialog = FileNameInputDialog(this)

        // 获取传递的应用信息
        appInfo = intent.getParcelableExtra<AppInfo>("app_info") ?: run {
            finish()
            return
        }

        // 设置工具栏
        setSupportActionBar(findViewById(R.id.toolbar))
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 初始化视图（先显示基本信息）
        initViewsWithBasicInfo()
        
        // 后台加载完整应用信息
        loadDetailedAppInfo()
    }

    private fun initViewsWithBasicInfo() {
        // 设置应用图标和基本信息
        val ivAppIcon = findViewById<ImageView>(R.id.iv_app_icon)
        val tvAppName = findViewById<TextView>(R.id.tv_app_name)
        val tvPackageName = findViewById<TextView>(R.id.tv_package_name)
        val tvDetails = findViewById<TextView>(R.id.tv_details)

        // 由于Drawable不能通过Parcelable传递，需要重新加载应用图标
        try {
            val packageManager = packageManager
            val applicationInfo = packageManager.getApplicationInfo(appInfo.packageName, 0)
            ivAppIcon.setImageDrawable(packageManager.getApplicationIcon(applicationInfo))
        } catch (e: Exception) {
            // 如果加载失败，使用默认图标
            ivAppIcon.setImageResource(android.R.drawable.sym_def_app_icon)
        }
        
        tvAppName.text = appInfo.appName
        tvPackageName.text = appInfo.packageName

        // 设置基本信息（列表加载时已经获取的信息）
        val appName = "应用名称: ${appInfo.appName}"
        val packageName = "包名: ${appInfo.packageName}"
        val systemApp = "系统应用: ${if (appInfo.isSystemApp) "是" else "否"}"
        
        // 其他信息显示为"加载中..."
        val version = "版本: 加载中..."
        val size = "大小: 加载中..."
        val targetSdk = "目标SDK: 加载中..."
        val minSdk = "最小SDK: 加载中..."
        val architecture = "架构支持: 加载中..."
        val installTime = "安装时间: 加载中..."
        val updateTime = "更新时间: 加载中..."
        val signature = "签名信息: 加载中..."

        // 创建SpannableString
        val spannableString = android.text.SpannableStringBuilder()
        
        // 添加应用名称和复制图标
        spannableString.append(appName)
        spannableString.append("  ")
        val appNameCopyIcon = "📋"
        val appNameStart = spannableString.length
        spannableString.append(appNameCopyIcon)
        val appNameEnd = spannableString.length
        
        // 创建ImageSpan用于应用名称的复制图标
        val appNameDrawable = resources.getDrawable(R.drawable.ic_copy, null)
        appNameDrawable.setBounds(0, 0, appNameDrawable.intrinsicWidth, appNameDrawable.intrinsicHeight)
        val appNameImageSpan = android.text.style.ImageSpan(appNameDrawable, android.text.style.ImageSpan.ALIGN_BASELINE)
        
        spannableString.setSpan(object : android.text.style.ClickableSpan() {
            override fun onClick(widget: View) {
                copyToClipboard(appInfo.appName, "应用名称")
            }
            
            override fun updateDrawState(ds: android.text.TextPaint) {
                super.updateDrawState(ds)
                ds.color = android.graphics.Color.TRANSPARENT // 设置文本颜色为透明
                ds.isUnderlineText = false // 去掉下划线
            }
        }, appNameStart, appNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 替换表情符号为ImageSpan
        spannableString.setSpan(appNameImageSpan, appNameStart, appNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.append("\n")
        
        // 添加包名和复制图标
        spannableString.append(packageName)
        spannableString.append("  ")
        val packageNameCopyIcon = "📋"
        val packageNameStart = spannableString.length
        spannableString.append(packageNameCopyIcon)
        val packageNameEnd = spannableString.length
        
        // 创建ImageSpan用于包名的复制图标
        val packageNameDrawable = resources.getDrawable(R.drawable.ic_copy, null)
        packageNameDrawable.setBounds(0, 0, packageNameDrawable.intrinsicWidth, packageNameDrawable.intrinsicHeight)
        val packageNameImageSpan = android.text.style.ImageSpan(packageNameDrawable, android.text.style.ImageSpan.ALIGN_BASELINE)
        
        spannableString.setSpan(object : android.text.style.ClickableSpan() {
            override fun onClick(widget: View) {
                copyToClipboard(appInfo.packageName, "包名")
            }
            
            override fun updateDrawState(ds: android.text.TextPaint) {
                super.updateDrawState(ds)
                ds.color = android.graphics.Color.TRANSPARENT // 设置文本颜色为透明
                ds.isUnderlineText = false // 去掉下划线
            }
        }, packageNameStart, packageNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 替换表情符号为ImageSpan
        spannableString.setSpan(packageNameImageSpan, packageNameStart, packageNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.append("\n")
        
        // 添加其他信息
        spannableString.append("$version\n")
        spannableString.append("$size\n")
        spannableString.append("$targetSdk\n")
        spannableString.append("$minSdk\n")
        spannableString.append("$architecture\n")
        spannableString.append("$systemApp\n")
        spannableString.append("$installTime\n")
        spannableString.append(updateTime)
        spannableString.append("\n")
        
        // 添加签名信息和复制图标
        spannableString.append(signature)
        spannableString.append("  ")
        val signatureCopyIcon = "📋"
        val signatureStart = spannableString.length
        spannableString.append(signatureCopyIcon)
        val signatureEnd = spannableString.length
        
        // 创建ImageSpan用于签名的复制图标
        val signatureDrawable = resources.getDrawable(R.drawable.ic_copy, null)
        signatureDrawable.setBounds(0, 0, signatureDrawable.intrinsicWidth, signatureDrawable.intrinsicHeight)
        val signatureImageSpan = android.text.style.ImageSpan(signatureDrawable, android.text.style.ImageSpan.ALIGN_BASELINE)
        
        spannableString.setSpan(object : android.text.style.ClickableSpan() {
            override fun onClick(widget: View) {
                copyToClipboard(appInfo.signatureInfo ?: "", "签名信息")
            }
            
            override fun updateDrawState(ds: android.text.TextPaint) {
                super.updateDrawState(ds)
                ds.color = android.graphics.Color.TRANSPARENT // 设置文本颜色为透明
                ds.isUnderlineText = false // 去掉下划线
            }
        }, signatureStart, signatureEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 替换表情符号为ImageSpan
        spannableString.setSpan(signatureImageSpan, signatureStart, signatureEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 设置TextView的文本和移动方法
        tvDetails.text = spannableString
        tvDetails.movementMethod = android.text.method.LinkMovementMethod.getInstance()

        // 设置按钮点击事件
        val btnExport = findViewById<View>(R.id.btn_export)
        val btnExtractIcon = findViewById<View>(R.id.btn_extract_icon)
        val btnUninstall = findViewById<View>(R.id.btn_uninstall)

        // 导出应用按钮
        btnExport.setOnClickListener {
            exportApp()
        }

        // 提取图标按钮
        btnExtractIcon.setOnClickListener {
            extractAppIcon()
        }

        // 卸载应用按钮
        btnUninstall.setOnClickListener {
            uninstallApp()
        }

        // 如果是系统应用，禁用卸载按钮
        if (appInfo.isSystemApp) {
            btnUninstall.isEnabled = false
            btnUninstall.alpha = 0.5f
        }
    }

    /**
     * 后台加载完整的应用信息
     * 这是性能优化的关键部分 - 只在需要显示详情时才加载耗时信息
     */
    private fun loadDetailedAppInfo() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 调用AppScanner获取完整的应用信息
                val detailedAppInfo = appScanner.getAppDetailedInfo(appInfo.packageName)
                
                withContext(Dispatchers.Main) {
                    hideLoading()
                    
                    if (detailedAppInfo != null) {
                        // 更新appInfo对象
                        appInfo = detailedAppInfo
                        
                        // 更新UI显示完整信息
                        updateUIWithDetailedInfo()
                    } else {
                        Toast.makeText(this@AppDetailActivity, "加载应用详情失败", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    hideLoading()
                    Toast.makeText(this@AppDetailActivity, "加载应用详情失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    
    /**
     * 使用加载到的完整信息更新UI
     */
    private fun updateUIWithDetailedInfo() {
        val tvDetails = findViewById<TextView>(R.id.tv_details)
        
        // 创建包含完整信息的SpannableString
        val spannableString = android.text.SpannableStringBuilder()
        
        // 添加应用名称和复制图标
        val appName = "应用名称: ${appInfo.appName}"
        spannableString.append(appName)
        spannableString.append("  ")
        val appNameCopyIcon = "📋"
        val appNameStart = spannableString.length
        spannableString.append(appNameCopyIcon)
        val appNameEnd = spannableString.length
        
        // 创建ImageSpan用于应用名称的复制图标
        val appNameDrawable = resources.getDrawable(R.drawable.ic_copy, null)
        appNameDrawable.setBounds(0, 0, appNameDrawable.intrinsicWidth, appNameDrawable.intrinsicHeight)
        val appNameImageSpan = android.text.style.ImageSpan(appNameDrawable, android.text.style.ImageSpan.ALIGN_BASELINE)
        
        spannableString.setSpan(object : android.text.style.ClickableSpan() {
            override fun onClick(widget: View) {
                copyToClipboard(appInfo.appName, "应用名称")
            }
            
            override fun updateDrawState(ds: android.text.TextPaint) {
                super.updateDrawState(ds)
                ds.color = android.graphics.Color.TRANSPARENT // 设置文本颜色为透明
                ds.isUnderlineText = false // 去掉下划线
            }
        }, appNameStart, appNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 替换表情符号为ImageSpan
        spannableString.setSpan(appNameImageSpan, appNameStart, appNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.append("\n")
        
        // 添加包名和复制图标
        val packageName = "包名: ${appInfo.packageName}"
        spannableString.append(packageName)
        spannableString.append("  ")
        val packageNameCopyIcon = "📋"
        val packageNameStart = spannableString.length
        spannableString.append(packageNameCopyIcon)
        val packageNameEnd = spannableString.length
        
        // 创建ImageSpan用于包名的复制图标
        val packageNameDrawable = resources.getDrawable(R.drawable.ic_copy, null)
        packageNameDrawable.setBounds(0, 0, packageNameDrawable.intrinsicWidth, packageNameDrawable.intrinsicHeight)
        val packageNameImageSpan = android.text.style.ImageSpan(packageNameDrawable, android.text.style.ImageSpan.ALIGN_BASELINE)
        
        spannableString.setSpan(object : android.text.style.ClickableSpan() {
            override fun onClick(widget: View) {
                copyToClipboard(appInfo.packageName, "包名")
            }
            
            override fun updateDrawState(ds: android.text.TextPaint) {
                super.updateDrawState(ds)
                ds.color = android.graphics.Color.TRANSPARENT // 设置文本颜色为透明
                ds.isUnderlineText = false // 去掉下划线
            }
        }, packageNameStart, packageNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 替换表情符号为ImageSpan
        spannableString.setSpan(packageNameImageSpan, packageNameStart, packageNameEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.append("\n")
        
        // 添加其他完整信息
        val version = "版本: ${appInfo.versionName} (${appInfo.versionCode})"
        val size = "大小: ${FileUtils.formatFileSize(appInfo.apkSize)}"
        val targetSdk = "目标SDK: ${appInfo.targetSdkVersion}"
        val minSdk = "最小SDK: ${appInfo.minSdkVersion}"
        val architecture = "架构支持: ${getArchitectureSupportText(appInfo.supports32Bit, appInfo.supports64Bit)}"
        val systemApp = "系统应用: ${if (appInfo.isSystemApp) "是" else "否"}"
        val installTime = "安装时间: ${FileUtils.formatDate(appInfo.installTime)}"
        val updateTime = "更新时间: ${FileUtils.formatDate(appInfo.updateTime)}"
        val signature = "签名信息: ${appInfo.signatureInfo ?: "未知"}"
        
        spannableString.append("$version\n")
        spannableString.append("$size\n")
        spannableString.append("$targetSdk\n")
        spannableString.append("$minSdk\n")
        spannableString.append("$architecture\n")
        spannableString.append("$systemApp\n")
        spannableString.append("$installTime\n")
        spannableString.append(updateTime)
        spannableString.append("\n")
        
        // 添加签名信息和复制图标
        spannableString.append(signature)
        spannableString.append("  ")
        val signatureCopyIcon = "📋"
        val signatureStart = spannableString.length
        spannableString.append(signatureCopyIcon)
        val signatureEnd = spannableString.length
        
        // 创建ImageSpan用于签名的复制图标
        val signatureDrawable = resources.getDrawable(R.drawable.ic_copy, null)
        signatureDrawable.setBounds(0, 0, signatureDrawable.intrinsicWidth, signatureDrawable.intrinsicHeight)
        val signatureImageSpan = android.text.style.ImageSpan(signatureDrawable, android.text.style.ImageSpan.ALIGN_BASELINE)
        
        spannableString.setSpan(object : android.text.style.ClickableSpan() {
            override fun onClick(widget: View) {
                copyToClipboard(appInfo.signatureInfo ?: "", "签名信息")
            }
            
            override fun updateDrawState(ds: android.text.TextPaint) {
                super.updateDrawState(ds)
                ds.color = android.graphics.Color.TRANSPARENT // 设置文本颜色为透明
                ds.isUnderlineText = false // 去掉下划线
            }
        }, signatureStart, signatureEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 替换表情符号为ImageSpan
        spannableString.setSpan(signatureImageSpan, signatureStart, signatureEnd, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        
        // 设置TextView的文本和移动方法
        tvDetails.text = spannableString
        tvDetails.movementMethod = android.text.method.LinkMovementMethod.getInstance()
    }
    
    private fun getArchitectureSupportText(supports32Bit: Boolean, supports64Bit: Boolean): String {
        return when {
            supports32Bit && supports64Bit -> "32位 & 64位"
            supports32Bit -> "32位"
            supports64Bit -> "64位"
            else -> "未知"
        }
    }

    private fun openApp() {
        try {
            val intent = packageManager.getLaunchIntentForPackage(appInfo.packageName)
            if (intent != null) {
                startActivity(intent)
            } else {
                Toast.makeText(this, "无法启动该应用", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "启动应用失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun uninstallApp() {
        if (appInfo.isSystemApp) {
            Toast.makeText(this, "无法卸载系统应用", Toast.LENGTH_SHORT).show()
            return
        }

        try {
            // 先注销之前的接收器（如果存在）
            uninstallReceiver?.let {
                try {
                    unregisterReceiver(it)
                } catch (e: Exception) {
                    // 忽略未注册的接收器异常
                }
                uninstallReceiver = null
            }
            
            // 注册卸载完成的广播接收器
            val packageName = appInfo.packageName
            uninstallReceiver = object : android.content.BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    val removedPackage = intent.data?.schemeSpecificPart
                    if (removedPackage == packageName) {
                        // 卸载完成，关闭当前页面即可，不需要显式返回首页
                        try {
                            context.unregisterReceiver(this)
                        } catch (e: Exception) {
                            // 忽略未注册的接收器异常
                        }
                        uninstallReceiver = null
                        
                        // 设置结果码，通知MainActivity刷新应用列表
                        setResult(RESULT_OK)
                        finish()
                    }
                }
            }
            
            // 注册广播接收器
            val filter = android.content.IntentFilter(Intent.ACTION_PACKAGE_REMOVED)
            filter.addDataScheme("package")
            registerReceiver(uninstallReceiver, filter)
            
            // 启动卸载
            val intent = Intent(Intent.ACTION_DELETE)
            intent.data = android.net.Uri.parse("package:${appInfo.packageName}")
            startActivity(intent)
        } catch (e: Exception) {
            Toast.makeText(this, "卸载失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun exportApp() {
        // 检查权限
        if (!PermissionHelper.hasStoragePermissions(this)) {
            // 显示权限说明弹窗
            androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle(R.string.permission_storage_title)
                .setMessage("需要存储权限来导出应用文件。\n\n授予权限后，您可以将应用导出到指定目录。")
                .setPositiveButton("授予权限") { _, _ ->
                    requestStoragePermissions { granted ->
                        if (granted) {
                            proceedWithExport()
                        } else {
                            Toast.makeText(this, "需要存储权限才能导出应用", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                .setNegativeButton("取消", null)
                .show()
            return
        }

        proceedWithExport()
    }
    
    private fun proceedWithExport() {
        fileNameInputDialog.showSingleAppFileNameDialog(appInfo) { customFileName ->
            val exportDirectory = FileUtils.getExportDirectory(this@AppDetailActivity)
            lifecycleScope.launch {
                try {
                    // 确保自定义文件名被正确传递
                    val result = appExporter.exportApp(
                        appInfo = appInfo, 
                        exportDirectory = exportDirectory, 
                        customFileName = customFileName
                    )
                    hideLoading()
                    showExportResultDialog(result)
                } catch (e: Exception) {
                    hideLoading()
                    Toast.makeText(this@AppDetailActivity, "导出失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    
    private fun requestStoragePermissions(callback: (Boolean) -> Unit) {
        // 设置回调
        permissionCallback = callback
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val intent = PermissionHelper.getStoragePermissionIntent(this)
            manageStorageLauncher.launch(intent)
        } else {
            val permissions = PermissionHelper.getRequiredPermissions()
            if (permissions.isNotEmpty()) {
                storagePermissionLauncher.launch(permissions)
            } else {
                callback(true)
            }
        }
    }
    
    private fun extractAppIcon() {
        // 检查权限，使用与导出功能相同的权限检查逻辑
        if (!PermissionHelper.hasStoragePermissions(this)) {
            // 显示权限说明弹窗
            androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle(R.string.permission_storage_title)
                .setMessage("需要存储权限来提取应用图标。\n\n授予权限后，您可以将图标保存到指定目录。")
                .setPositiveButton("授予权限") { _, _ ->
                    requestStoragePermissions { granted ->
                        if (granted) {
                            proceedWithIconExtraction()
                        } else {
                            Toast.makeText(this, "需要存储权限才能提取图标", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                .setNegativeButton("取消", null)
                .show()
            return
        }

        proceedWithIconExtraction()
    }
    
    private fun proceedWithIconExtraction() {
        // 执行图标提取
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 获取应用图标
                val packageManager = packageManager
                val applicationInfo = packageManager.getApplicationInfo(appInfo.packageName, 0)
                val appIcon = packageManager.getApplicationIcon(applicationInfo)
                
                // 使用用户设置的目录直接导出图标
                val exportDir = File(FileUtils.getExportDirectory(this@AppDetailActivity))
                if (!exportDir.exists()) {
                    exportDir.mkdirs()
                }
                
                // 生成图标文件名
                val sanitizedName = FileUtils.sanitizeFileName(appInfo.appName)
                val iconFile = File(exportDir, "${sanitizedName}_${appInfo.packageName}.png")
                
                // 将图标保存为PNG文件
                val bitmap = android.graphics.Bitmap.createBitmap(
                    appIcon.intrinsicWidth,
                    appIcon.intrinsicHeight,
                    android.graphics.Bitmap.Config.ARGB_8888
                )
                val canvas = android.graphics.Canvas(bitmap)
                appIcon.setBounds(0, 0, canvas.width, canvas.height)
                appIcon.draw(canvas)
                
                java.io.FileOutputStream(iconFile).use { out ->
                    bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)
                }
                
                // 回到主线程显示结果
                withContext(Dispatchers.Main) {
                    val dialog = androidx.appcompat.app.AlertDialog.Builder(this@AppDetailActivity)
                        .setTitle("图标已保存")
                        .setMessage(iconFile.absolutePath)
                        .setPositiveButton("确定", null)
                        .setNegativeButton("分享") { _, _ ->
                            try {
                                // 使用FileProvider分享图标文件
                                val shareIntent = Intent(Intent.ACTION_SEND)
                                shareIntent.type = "image/png"
                                
                                // 使用FileProvider获取内容URI
                                val contentUri = androidx.core.content.FileProvider.getUriForFile(
                                    this@AppDetailActivity,
                                    "${packageName}.fileprovider",  // 使用正确的authority
                                    iconFile
                                )
                                
                                shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri)
                                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                startActivity(Intent.createChooser(shareIntent, "分享图标"))
                            } catch (e: Exception) {
                                Toast.makeText(
                                    this@AppDetailActivity,
                                    "无法分享图标: ${e.message}",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                        .create()
                    
                    dialog.show()
                }
                
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@AppDetailActivity, "提取图标失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    
    private fun copyToClipboard(text: String, label: String) {
        val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clip = android.content.ClipData.newPlainText(label, text)
        clipboard.setPrimaryClip(clip)
        Toast.makeText(this, "$label 已复制到剪贴板", Toast.LENGTH_SHORT).show()
    }

    private fun showLoading(message: String) {
        // 简单的加载提示，可以根据需要使用更复杂的加载对话框
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
    
    private fun hideLoading() {
        // 隐藏加载提示
    }

    private fun showExportResultDialog(result: AppExporter.ExportResult) {
        exportResultDialogHelper.showExportResultDialog(result)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 注销广播接收器，避免内存泄漏
        uninstallReceiver?.let {
            try {
                unregisterReceiver(it)
            } catch (e: Exception) {
                // 忽略未注册的接收器异常
            }
            uninstallReceiver = null
        }
    }
}